#include "form_directory_dlg.h"
#include "ui_form_directory_dlg.h"

#include "ui/share/form_prompt_dlg.h"

static int s_nReplyType = 0;

/*
 * Function:    FormDirectoryDlg
 * Description: The default constructor
 * Paramer:     void
 * Return:
 */
FormDirectoryDlg::FormDirectoryDlg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FormDirectoryDlg)
{
    qDebug() << Q_FUNC_INFO;

    ui->setupUi(this);
}

/*
 * FormDirectoryDlg:    ~FormDirectoryDlg
 * Description: The default destructor
 * Paramer:     void
 * Return:
 */
FormDirectoryDlg::~FormDirectoryDlg()
{
    qDebug() << Q_FUNC_INFO;

    delete ui;
}

/*
 * Function:    getInstance
 * Description: Get an instance of "FormDirectoryDlg" class, if exist, return it
 * Paramer:     QWidget *pParent - the pointer of QWidget class
 * Return:      the pointer of "FormDirectoryDlg" class
 */
FormDirectoryDlg* FormDirectoryDlg::getInstance(QWidget *pParent)
{
    static FormDirectoryDlg *pNew = NULL;
    if(!pNew) {
        qDebug() << Q_FUNC_INFO;

        // Create a new object if it doesn't exist
        pNew = new FormDirectoryDlg(pParent);
        if(NULL == pNew) return NULL;

        // After constructing object, initialize the object
        pNew->_initObj();

        // Initialize control's UI
        pNew->_InitUi();

        // Hide widget firstly
        pNew->hide();
    }
    else {
        // Set the parent object
        pNew->setParent(pParent);
    }

    return pNew;
}

/*
 * Function:    _initObj
 * Description: After constructing object, initialize the object
 * Paramer:     void
 * Return:      void
 */
void FormDirectoryDlg::_initObj()
{
    qDebug() << Q_FUNC_INFO;

    if(!m_pModelFiles) m_pModelFiles = new QStandardItemModel(this);

    std::vector<bool> vecConnect;
    vecConnect.push_back(QObject::connect(ui->listView_Directory, SIGNAL(doubleClicked(const QModelIndex &)), ui->pushButton_Confirm, SIGNAL(clicked())));
    for(int i=0; i<(int)vecConnect.size(); i++) {
        Q_ASSERT(vecConnect.at(i));
    }
}

/*
* Function:		_InitUi
* Description:	Init the window style
* Paramer:		void
* Return:		void
*/
void FormDirectoryDlg::_InitUi()
{
    qDebug() << Q_FUNC_INFO;

    // Displays the background image of the window
    QWidget::setAttribute(Qt::WA_StyledBackground);

    SET_STYLE_SHEET(QString(":/%1/factory/%2.qss").arg("skin_1").arg(this->objectName()));

    ui->pushButton_Confirm->setFocusPolicy(Qt::NoFocus);
    ui->pushButton_Cancel->setFocusPolicy(Qt::NoFocus);
}

/*
* Function:		changeEvent
* Description:	Triggers an event before it is switch language
* Paramer:		QShowEvent *event - the pointer of "QEvent"
* Return:		void
*/
void FormDirectoryDlg::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);

    switch (e->type())
    {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);

        qDebug() << Q_FUNC_INFO;
        break;
    default:
        break;
    }
}

/*
* Function:		on_pushButton_Save_clicked
* Description:	Save the basic info after click the button
* Paramer:		void
* Return:		void
*/
void FormDirectoryDlg::on_pushButton_Confirm_clicked()
{
    qDebug() << Q_FUNC_INFO;

    QModelIndex idxModel = ui->listView_Directory->currentIndex();
    if(idxModel.isValid()) {
        QString sFileName = ((QStandardItemModel*)ui->listView_Directory->model())->itemFromIndex(idxModel)->text().trimmed();
        if(!sFileName.isEmpty()) {
            qDebug() << Q_FUNC_INFO << sFileName;

            // Signal-slot initialization
            bool bCon = QObject::connect(this, SIGNAL(signalReplayInfo(int, bool, QString)), this->parent(), SLOT(slotRespondInfoFromDlgEx(int, bool, QString)));
            Q_ASSERT(bCon);

            QTimer::singleShot(10, this, [=]{
                this->hide();
            });

            emit signalReplayInfo(s_nReplyType, true, sFileName);

            // Signal-slot disconnect
            QObject::disconnect(this, SIGNAL(signalReplayInfo(int, bool, QString)), this->parent(), SLOT(slotRespondInfoFromDlgEx(int, bool, QString)));

        }
        else {
            FormPromptWidget::getInstance(this->parentWidget())->setPromptInfo(tr("Prompt"), tr("Invalid procedure file"));
        }
    }
    else {
        FormPromptWidget::getInstance(this->parentWidget())->setPromptInfo(tr("Prompt"), tr("Please select a procedure file"));
    }
}

/*
* Function:		on_pushButton_Cancel_clicked
* Description:	Close the window after click the button
* Paramer:		void
* Return:		void
*/
void FormDirectoryDlg::on_pushButton_Cancel_clicked()
{
    qDebug() << Q_FUNC_INFO;

    this->hide();
}

/*
 * Function:    displayWindow
 * Description: Set procedure name and display the page
 * Paramer:     int nReplyType - the operate type of procedure
 *              QString sFileName - the data file name
 *              bool bNewProcedure - Is a new procedure ?
 * Return:      void
 */
void FormDirectoryDlg::displayWindow(int nReplyType, QString sContent, QString sFilter)
{
    qDebug() << Q_FUNC_INFO << nReplyType << sContent << sFilter;
    s_nReplyType = nReplyType;
    sContent = sContent.trimmed();

    m_pModelFiles->clear();
    ui->listView_Directory->setModel(nullptr);

    QStringList lstFiles;
    int nFileCnt = _listFilesInDirectory(lstFiles, sContent, sFilter);
    if(0 < nFileCnt) {
        ui->pushButton_Confirm->setEnabled(true);

        foreach(auto var, lstFiles) {
            QStandardItem *pItem = new QStandardItem(QIcon(DEF_STEP_ICON_FILE2), var);
            m_pModelFiles->appendRow(pItem);
        }

        ui->listView_Directory->setModel(m_pModelFiles);
        ui->listView_Directory->setViewMode(QListView::IconMode);
        ui->listView_Directory->setIconSize(QSize(48, 48));
        ui->listView_Directory->setGridSize(QSize(200, 84));
        ui->listView_Directory->setMovement(QListView::Static);
        ui->listView_Directory->setSelectionMode(QAbstractItemView::SingleSelection);
        ui->listView_Directory->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->listView_Directory->setFlow(QListView::LeftToRight);
        ui->listView_Directory->setFocusPolicy(Qt::NoFocus);
        ui->listView_Directory->scrollToTop();

    }
    else {
        ui->pushButton_Confirm->setEnabled(false);
    }

    this->show();
}

int FormDirectoryDlg::_listFilesInDirectory(QStringList &lstFiles, const QString &sPath, const QString sSuffix)
{
    lstFiles.clear();

    qDebug() << Q_FUNC_INFO << sPath << sSuffix;
    QString sFilter = "*." + sSuffix;

    int nRetVal = 0;

    lstFiles << sPath;
    nRetVal = lstFiles.size();

    if(0 != 0) {
        QDir dir(sPath);
        if (!dir.exists()) {
            qDebug() << "The directory does not exist!";
        }
        else {
            QStringList filters;
            filters << sFilter ;
            dir.setFilter(QDir::Files | QDir::NoDotAndDotDot);
            dir.setNameFilters(filters);

            QStringList fileList = dir.entryList();
            foreach (const QString &fileName, fileList) {
                lstFiles << fileName;
            }

            nRetVal = lstFiles.size();
        }
    }

    qDebug() << Q_FUNC_INFO << nRetVal;
    return nRetVal;
}
